<template>
  <div class="admin-dashboard">
    <el-card class="welcome-card">
      <div class="welcome-content">
        <h2>欢迎回来，{{ adminName }}</h2>
        <p>今天是 {{ today | formatDate }}</p>
        <div class="stats-container">
          <el-statistic
              class="stat-item"
              title="总用户数"
              :value="totalUsers"
              :precision="0"
          >
            <template #prefix>
              <User />
            </template>
          </el-statistic>
          <el-statistic
              class="stat-item"
              title="水果总数"
              :value="totalFruits"
              :precision="0"
          >
            <template #prefix>
              <Box />
            </template>
          </el-statistic>
          <el-statistic
              class="stat-item"
              title="订单总数"
              :value="totalOrders"
              :precision="0"
          >
            <template #prefix>
              <ShoppingCart />
            </template>
          </el-statistic>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { User, Box, ShoppingCart } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import dashboardApi from '@/api/dashboard_api.js';

// 管理员名称
const adminName = ref('管理员');

// 统计数据
const totalUsers = ref(0);
const totalFruits = ref(0);
const totalOrders = ref(0);

// 格式化日期过滤器
const formatDate = (value) => {
  const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
  return value.toLocaleDateString('zh-CN', options);
};

// 今天日期
const today = ref(new Date());

// 加载统计数据
const loadDashboardData = async () => {
  try {
    const res = await dashboardApi.getStats();
    totalUsers.value = res.data.totalUsers || 0;
    totalFruits.value = res.data.totalFruits || 0;
    totalOrders.value = res.data.totalOrders || 0;
  } catch (error) {
    ElMessage.error('加载统计数据失败');
    console.error(error);
  }
};

onMounted(() => {
  // 从本地存储获取管理员信息
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  if (userInfo.username) {
    adminName.value = userInfo.username;
  }

  // 加载数据
  loadDashboardData();
});
</script>

<style scoped>
.admin-dashboard {
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
}

.welcome-content {
  padding: 20px;
}

.welcome-content h2 {
  margin-bottom: 10px;
  color: #2e7d32;
}

.welcome-content p {
  color: #666;
  margin-bottom: 20px;
}

.stats-container {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.stat-item {
  flex: 1;
  min-width: 200px;
  padding: 15px;
  background-color: #f9fef9;
  border-radius: 8px;
}

:deep(.el-statistic__content) {
  font-size: 24px;
  color: #2e7d32;
}

:deep(.el-statistic__label) {
  color: #666;
}
</style>